package chat.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * Listens on a given Socket.
 * Transfer the messages thats 
 * on the socket to a given
 * client.
 * @author Johan
 *
 */
public class SocketListner extends Thread{
	private BufferedReader read;
	private boolean on = true;
	private SocketClient client;
	
	/**
	 * Initiate the listener and starts it
	 * @param s - A socket
	 * @param c - SocketClient
	 * @throws IOException - If it's not able to listen to socket
	 */
	public SocketListner(Socket s, SocketClient c) throws IOException {
		client = c;
		read = new BufferedReader(new InputStreamReader(s.getInputStream()));
		start();
	}
	/**
	 * The main loop that listens to the socket.
	 */
	public void run() {
		while(on){
			try {
				client.receive(read.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * Kills the thread and closes the reader.
	 */
	@SuppressWarnings("deprecation")
	public void destroy() {
		super.stop();
		try {
			read.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
